package common.store.admin.dao;


import common.store.admin.dto.Category;
import common.store.common.util.C3p0Pool;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class CategoryDao {

    static QueryRunner qr;

    static {
        qr = new QueryRunner(C3p0Pool.getDataSource());

    }
    public List<Category> getCategoryList() {
        try {
            return qr.query("select c.cid , c.cname from category c" , new BeanListHandler<>(Category.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Collections.EMPTY_LIST;
    }

    public Integer delCategoryByCid(String cid) {
        try {
            return qr.update("delete from category  where cid = ?" , cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public Integer addCategory(Category category) {
        try {
            return qr.update("insert into category values(? , ?)" , category.getCid() , category.getCname());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public Category getCategoryByCid(String cid) {

        try {
            //返回一条分类信息记录
            return qr.query("select c.cid , c.cname from category c where c.cid = ?" , new BeanHandler<>(Category.class) , cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Integer updateCategory(String cid, String cname) {
        try {
            return qr.update("update category set cname = ? where cid = ?" , cname , cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}